<style scoped>
</style>
<template>
  <van-field v-bind="$attrs"
             :placeholder="placeholder"
             :model-value="content"
             readonly >
    <template #input>
      <div v-if="is_info">
        <van-tag type="primary" size="medium" v-for="v in content_arr">{{ v }}</van-tag>
      </div>
      <div v-else>
        <input type="hidden" :name="name" :value="modelValue">
        <van-checkbox-group direction="horizontal" v-model="value_arr" @change="change">
          <van-checkbox v-for="row in options" :name="row.value" shape="square">{{ row.content }}</van-checkbox>
        </van-checkbox-group>
      </div>
    </template>
  </van-field>
</template>

<script>
import s94 from "s94-js";
import {decode_config} from "@/js/s94_tool.js";

export default {
  name: "checkbox",
  props: {
    name: String,
    modelValue: [String,Number],
    config: [String,Object],
    placeholder: String,
    is_info: Boolean,
  },
  emits: ['update:modelValue','change'],
  data(){
    return {
      need_display: true, //定义当modelValue变动时是否需要渲染，用来阻止当前组件变动 modelValue 后重新渲染
      options: [],
      content: "",
      value_arr: [],
      option_arr: [],
    }
  },
  methods: {
    display(){
      let options = decode_config(this.config);
      this.options = options;

      this.value_arr = [];
      let val = s94.to_string(this.modelValue);
      if (val) this.value_arr = val.split(",");
    },
    change(value_arr){
      let val = value_arr.length ? value_arr.join(",") : "";
      this.need_display = false;
      setTimeout(()=>{this.need_display=true},10)
      this.$emit('update:modelValue', val);
      this.$emit('change', val);
    }
  },
  watch: {
    config(v){
      this.display();
    },
    modelValue(){
      if (this.need_display) this.display();
    },
  },
  computed: {
    content_arr(){
      if (!this.value_arr.length) return [];
      let res = [].concat(this.value_arr);
      s94.eachloop(this.options, 'children', (row)=>{
        let i = this.value_arr.indexOf(row.value);
        if (i!==-1) res[i] = row.content;
        return true;
      })
      return res;
    }
  },
  mounted() {
    this.display();
  }
}
</script>